import wtforms
from wtforms import (Form, StringField, validators, IntegerField)
from models import (EmailCaptchaModel, UserModel)


class RegisterForm(Form):
    username = StringField(validators=[validators.length(min=3, max=20)])
    email = StringField(validators=[validators.email()])
    captcha = StringField(validators=[validators.length(min=4, max=4)])
    password = StringField(validators=[validators.length(min=6, max=20)])
    password_confirm = StringField(validators=[validators.EqualTo('password')])

    def validate_captcha(self, field):
        captcha = field.data
        captcha_model = EmailCaptchaModel.query.filter_by(email=self.email.data).first()

        if not captcha_model or captcha_model.captcha.lower() != captcha.lower():
            raise wtforms.ValidationError('邮箱验证码错误!')

    def validate_email(self, field):
        email = field.data
        user_model = UserModel.query.filter_by(email=email).first()
        if user_model:
            raise wtforms.ValidationError('邮箱已经存在!')


class LoginForm(Form):
    email = StringField(validators=[validators.email()])
    password = StringField(validators=[validators.length(min=6, max=20)])


class QuestionForm(Form):
    title = StringField(validators=[validators.length(min=3, max=200)])
    content = StringField(validators=[validators.length(min=5)])


class AnswerForm(Form):
    content = StringField(validators=[validators.length(min=5)])


class SearchForm(Form):
    keyword = StringField(validators=[validators.Length(min=1, max=20)])
